package com.adcc.loadsheet.billing.controller;

import com.adcc.aoc.devLib.common.log.Log;
import com.adcc.loadsheet.billing.entity.chargerule.BillingRuleEntity;
import com.adcc.loadsheet.billing.entity.contractuser.ContractUserEntity;
import com.adcc.loadsheet.billing.exception.ParamValidException;
import com.adcc.loadsheet.billing.exception.PermissionVerifyException;
import com.adcc.loadsheet.billing.service.BillingRuleService;
import com.adcc.loadsheet.billing.service.ContractUserService;
import com.adcc.loadsheet.billing.util.LogUtil;
import com.adcc.loadsheet.billing.validator.BillingRuleEntityVOValidator;
import com.adcc.loadsheet.billing.vo.ResultStatus;
import com.adcc.loadsheet.billing.vo.ResultVO;
import com.adcc.loadsheet.billing.vo.chargerule.BillingRuleEntityVO;
import com.adcc.loadsheet.billing.vo.chargerule.BillingRuleTreeVO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 计费规则管理Controller层
 * Created by zhaoml on 2020/4/2.
 */
@Controller
@RequestMapping(value = "billingrule")
@Api(value = "/billingrule", description = "计费规则相关操作controller")
public class BillingRuleController extends BasisController{
    @Autowired
    BillingRuleService billingRuleService;

    @Autowired
    ContractUserService contractUserService;

    @Autowired
    BillingRuleEntityVOValidator billingRuleEntityVOValidator;
    @InitBinder("billingRuleEntityVO")
    public void initBainder(WebDataBinder binder) {
        binder.replaceValidators(this.billingRuleEntityVOValidator);
    }

    /**
     * 进入计费规则管理页面
     *
     * @param model
     * @return
     */
    @PreAuthorize("hasPermission('','BillingRuleManage')")
    @GetMapping(value = "tobillingrulemanage")
    @ApiOperation(value = "/tobillingrulemanage", notes = "跳转到计费规则管理页面", httpMethod = "GET")
    public String toBillingRuleManage(Model model) {
        return "billingRule/billingrule-manage";
    }

    /**
     * 计费规则树状图
     *
     * @return
     */
    @RequestMapping(value = "/getBillingRuleTree", method = RequestMethod.GET)
    public @ResponseBody
    List<BillingRuleTreeVO> getBillingRuleTree() {
        List<BillingRuleTreeVO> list = Lists.newArrayList();
        try {
            //获取计费规则Tree（按照规则简称升序排列）
            list = billingRuleService.getTreeNode();
        } catch (Exception ex) {
            Log.error(BillingRuleController.class, "获取计费规则Tree出错", ex);
        }
        return list;
    }

    /**
     * 页面查询计费规则
     *
     * @param map
     * @return
     */
    @PostMapping(value = "findBillingRules", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiOperation(value = "/findBillingRules", notes = "查询计费规则", httpMethod = "POST")
    @ResponseBody
    public ResultVO findBillingRules(@RequestBody Map<String, Object> map) {
        ResultVO vo = new ResultVO();
        try {
            Map<String, Object> paramMap = inputBillingRuleParams(map);
            BillingRuleEntityVO billingRuleEntityVO = billingRuleService.findByBillingRuleId(paramMap);
            vo.getData().put("billingRuleEntityVO", billingRuleEntityVO);
        } catch (PermissionVerifyException pe) {
            vo.setStatus(ResultStatus.FAILED);
            vo.getData().put("msg", pe.getMessage());
        } catch (ParamValidException pe) {
            vo.setStatus(ResultStatus.FAILED);
            vo.getData().put("msg", pe.getMessage());
        } catch (Exception ex) {
            Log.error(BillingRuleController.class, "查询计费规则出错", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason(String.format(ResultVO.ER_CALL_EX_FAILED, "Query findBillingRules", ex.fillInStackTrace()));
        }
        return vo;
    }

    /**
     * 编辑计费规则
     *
     * @param billingRuleEntityVO
     * @param br
     * @return
     * @throws Exception
     */
    @PostMapping(value = "editBillingRule", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiOperation(value = "/editBillingRule", notes = "编辑计费规则", httpMethod = "POST")
    @ResponseBody
    public ResultVO editBillingRule(@Valid @RequestBody BillingRuleEntityVO billingRuleEntityVO,
                                    BindingResult br) throws Exception {
        ResultVO vo = new ResultVO();
        try {
            if (br.hasErrors()) {
                vo.setStatus(ResultStatus.FAILED);
                vo.setErrorReason(br.getAllErrors().get(0).getCode());
                return vo;
            }
            BillingRuleEntity billingRuleEntity = billingRuleService.edit(billingRuleEntityVO);
            vo.setStatus(ResultStatus.SUCCESS);
            vo.getData().put("msg", "编辑成功！");
            vo.getData().put("billingRuleId", billingRuleEntity.getBillingRuleId());
        } catch (Exception ex) {
            Log.error(BillingRuleController.class, "编辑计费规则出错", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason("编辑计费规则出错");
            LogUtil.errorLog(BillingRuleController.class, ex, "editBillingRule()");
        }
        return vo;
    }

    //判断计费规则是否被合同用户引用
    @PostMapping(value = "isBindContractUser", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    @ApiOperation(value = "/isBindContractUser", notes = "判断计费规则是否被合同用户引用", httpMethod = "POST")
    @ResponseBody
    public ResultVO isBindContractUser(@RequestBody BillingRuleEntityVO billingRuleEntityVO) throws Exception {
        ResultVO vo = new ResultVO();
        try {
            String res = "";
            Map<String, Object> map = Maps.newHashMap();
            map.put("billingRuleId",billingRuleEntityVO.getBillingRuleId());
            List<ContractUserEntity> contractUserEntityList = contractUserService.select(map);
            if(contractUserEntityList != null && contractUserEntityList.size() > 0){
                res = contractUserEntityList.get(0).getUserAbbrev();
            }
            vo.setStatus(ResultStatus.SUCCESS);
            vo.getData().put("msg", res);
        } catch (Exception ex) {
            Log.error(BillingRuleController.class, "判断计费规则是否被合同用户引用出错", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason("判断计费规则是否被合同用户引用出错");
        }
        return vo;
    }

    /**
     * 删除计费规则
     *
     * @param billingRuleId
     * @return
     */
    @GetMapping(value = "deleteBillingRule")
    @ApiOperation(value = "/deleteBillingRule", notes = "删除计费规则", httpMethod = "GET")
    @ResponseBody
    public ResultVO deleteBillingRule(Integer billingRuleId) {
        ResultVO vo = new ResultVO();
        String res = "";
        try {
            BillingRuleEntity billingRuleEntity = billingRuleService.findByBillingRuleId(billingRuleId);
            if (billingRuleEntity == null) {
                vo.setStatus(ResultStatus.FAILED);
                vo.setErrorReason("计费规则不存在！");
                return vo;
            }
            res = billingRuleService.deleteByBillingRuleId(billingRuleId);
            vo.setStatus(ResultStatus.SUCCESS);
            vo.getData().put("msg", res);
        } catch (Exception ex) {
            Log.error(BillingRuleController.class, "删除计费规则出错", ex);
            vo.setStatus(ResultStatus.FAILED);
            vo.setErrorReason("删除计费规则出错");
            LogUtil.errorLog(BillingRuleController.class,ex,"deleteBillingRule()");
        }
        return vo;
    }

    private Map<String, Object> inputBillingRuleParams(Map<String, Object> map) throws
            PermissionVerifyException, ParamValidException {
        Map<String, Object> paramMap = Maps.newHashMap();
        try {
            //计费规则主键ID
            Integer billingRuleId = map.get("billingRuleId") == null || "".equals(map.get("billingRuleId").toString()) ? null : Integer.valueOf(map.get("billingRuleId").toString());
            //第几页
            Integer pageNum = map.get("pageNum") == null || "".equals(map.get("pageNum")) ? 1 : Integer.parseInt(map.get("pageNum").toString());
            //每页页数
            Integer pageSize = map.get("pageSize") == null || "".equals(map.get("pageSize")) ? PAGE_SIZE_DEFAULT : Integer.parseInt(map.get("pageSize").toString());

            paramMap.put("billingRuleId", billingRuleId);
            paramMap.put("pageNum", pageNum);
            paramMap.put("pageSize", pageSize);
        } catch (Exception e) {
            throw new ParamValidException("输入参数错误");
        }
        return paramMap;
    }
}